package cn.javabb.web.controller.biz;

import cn.hutool.core.collection.CollUtil;
import cn.javabb.common.model.ResponseModel;
import cn.javabb.common.utils.ImageUtils;
import cn.javabb.common.utils.PageUtil;
import cn.javabb.common.utils.ResultUtil;
import cn.javabb.core.base.BaseController;
import cn.javabb.core.constant.BizConstant;
import cn.javabb.core.entity.biz.CommentDO;
import cn.javabb.core.entity.blog.BlogDO;
import cn.javabb.core.entity.blog.BlogTypeDO;
import cn.javabb.core.entity.sys.UserDO;
import cn.javabb.core.model.StatusEnum;
import cn.javabb.core.model.biz.PublishDateModel;
import cn.javabb.core.query.BlogQuery;
import cn.javabb.core.service.biz.CommentService;
import cn.javabb.core.service.blog.BlogService;
import cn.javabb.core.service.blog.BlogTypeService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @desc:
 * @author: javabb (javabob(a)163.com)
 * @create: 2019/12/01 19:38
 */
@Controller
@RequestMapping("/blog")
public class BlogController extends BaseController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogTypeService blogTypeService;
    @Autowired
    private CommentService commentService;
    /**
     * 	发布文章
     * @param blog
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/publish")
    public Object doPublish(BlogDO blog){

        blog.setUserId(getLoginUser().getId());
        if(StringUtils.isBlank(blog.getContent())) {
            return ResponseModel.Failure("保存失败，内容不能为空");
        }
        if(blogService.save(blog)) {
            return ResponseModel.Success("发布成功");
        }
        return ResponseModel.Failure("发布失败");
    }

    /**
     * 博客首页
     * @param query
     * @param model
     * @return
     */
    @GetMapping({"/","/blog",""})
    public ModelAndView index(BlogQuery query,Model model) {
        query.setTypeId(0);
        loadBlogData(query, model);
        return ResultUtil.view("web/view/blog/index");
    }

    /**
     * 分类
     * @param typeId
     * @param page
     * @param model
     * @return
     */
    @GetMapping("/{typeId}/{page}")
    public ModelAndView listByTypeId(@PathVariable Integer typeId,@PathVariable Integer page, Model model){
        BlogQuery query = new BlogQuery().setTypeId(typeId);
        query.setPage(page);
        query.setTypeId(typeId);
        loadBlogData(query,model);
        return ResultUtil.view("web/view/blog/index");
    }

    /**
     * 导入博客数据
     * @param query
     * @param model
     */
    public void loadBlogData(BlogQuery query, Model model) {
        // 博客
        PageInfo pageInfo = blogService.queryPage(query);
        List<BlogDO> blogs = pageInfo.getList();
        blogs.forEach(b->{
            List<String> thumImages = ImageUtils.getImageByHtml(b.getContent());
            if(CollUtil.isNotEmpty(thumImages)){
                b.setThumImages(thumImages.size()>3?thumImages.subList(0,2):thumImages);
            }
        });
        loadCommonData(model);
        model.addAttribute("blogs", blogs);
        // 生成分页
        String pagination = PageUtil.genPagination("/blog/"+query.getTypeId()+"/",pageInfo.getTotal(),query.getPage(),query.getSize());
        model.addAttribute("pagination", pagination);
    }

    /**
     * 导入公共数据
     * @param model
     */
    public void loadCommonData(Model model){
        // 按类别分类
        List<BlogTypeDO> blogTypes = blogTypeService.listWithBlogTotal();
        // 按时间分类
        List<PublishDateModel> listPublishDates = blogService.listPublishDates();
        model.addAttribute("blogTypes", blogTypes);
        model.addAttribute("listPublishDates", listPublishDates);
    }

    /**
     * 博客详细
     * @param blogId
     * @param model
     * @return
     */
    @GetMapping("/{blogId}")
    public ModelAndView detail(@PathVariable Integer blogId, Model model){

        BlogDO blog = blogService.get(blogId);
        if (blog ==null || blog.getState() != StatusEnum.NORMAL.getCode()) {
            model.addAttribute("queryString", "博客文章找不到或被禁用");
            return ResultUtil.error(404);
        }
        List<CommentDO> comments = commentService.listCommentsByBlogId(blogId);
        model.addAttribute("blog", blog);
        model.addAttribute("comments",comments);
        loadCommonData(model);
        return ResultUtil.view("web/view/blog/detail");
    }
    /*博客评论*/
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/comment")
    public Object comment(CommentDO comment) {
        if(comment.getArticleId()==null){
            return ResponseModel.Failure("参数错误",400);
        }
        if(StringUtils.isBlank(comment.getCommentContent())){
            return ResponseModel.Failure("评论内容不能为空");
        }
        if (!blogService.checkCommentAble(comment.getArticleId())) {
            return ResponseModel.Failure("当前文章不存在或者不支持评论");
        }
        UserDO loginUser = getLoginUser();
        comment.setUserId(loginUser.getId());
        comment.setParentId(comment.getParentId() == null ? -1 : comment.getParentId());
        comment.setArticleType(BizConstant.ARTICLE_TYPE_BLOG);
        comment.setCommentUsername(loginUser.getUserName());
        String result = commentService.saveComment(comment);
        if("insert".equals(result)){
            return ResponseModel.Success("评论成功");
        }else if("update".equals(result)){
            return ResponseModel.Success("修改成功");
        }

        return ResponseModel.Failure("评论失败");
    }

    /**
     * 个人中心博客管理
     */
    @RequiresAuthentication
    @ResponseBody
    @GetMapping("/list")
    public Object manage(BlogQuery query) {
        query.setUserId(getLoginUser().getId()); // 获取当前登录用户
        PageInfo p = blogService.queryPage(query);
        return ResponseModel.table(p);
    }

    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/del")
    public Object del(Integer id) {
        // 参数校验
        BlogDO blog = new BlogDO().setBlogId(id).setUserId(getLoginUser().getId());
        if (blogService.queryCountByWhere(blog)==0) {
            return ResponseModel.Failure("参数错误");
        }
        if(blogService.delete(String.valueOf(id))){
            return ResponseModel.Success("删除成功");
        }
        return ResponseModel.Failure("删除失败");
    }

}
